package com.tanhua.sso.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;

import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.sso.service.FaceEngineService;
import com.tanhua.sso.service.UserInfoService;
import com.tanhua.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    @Override
    public Boolean saveUserInfo(Map<String, String> param, String token) {
        //校验token
        User user = this.userService.queryUserByToken(token);
        if (user == null){
            return false;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"),"man")? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));
        userInfo.setNickName(param.get("nickname"));
//        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper();
        return userInfoMapper.insert(userInfo) == 1;
    }

    /**
     * 信息完善-头像
     * @param file
     * @param token
     * @return
     */
    @Override
    public Boolean saveUserLogo(MultipartFile file, String token) {
        //校验token
        User user = this.userService.queryUserByToken(token);
        if (user == null){
            return false;
        }


        try {
            //校验头像是否为人像
            boolean flag = this.faceEngineService.checkIsPortrait(file.getBytes());
            if (!flag){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //图片上传到阿里云OSS
        PicUploadResult uploadResult = this.picUploadService.upload(file);

        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(uploadResult.getName());

        //保存头像信息到表中
        /*LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getLogo,null);*/
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());

        return this.userInfoMapper.update(userInfo,queryWrapper) == 1;

    }

}
